package com.cgnpc.scp.adapter.controller;

import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.result.ApiResult;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cgnpc.scp.common.utils.JacksonUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.config.MockParam;
import com.cgnpc.scp.config.SpringContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/******************************
 * 创建时间: 2020/10/04 11:16
 ******************************/
@RestController
@RequestMapping("/scp/agent/adapter")
public class OuterAdapterController {

    private static final Logger LOGGER = LoggerFactory.getLogger(OuterAdapterController.class);

    @RequestMapping(value = "/outer", method = {RequestMethod.POST})
    @ResponseBody
    public Object outer(@RequestBody MockParam mockParam, HttpServletRequest request) {
        Object rs = null;
        try{
            LOGGER.info("outer invoke:{}------{}",mockParam.getBeanName(),mockParam.getMethodName());


            Object bean = SpringContextUtil.getBean(mockParam.getBeanName());

            LOGGER.info("bean:{}",bean);

            Method method = ReflectionUtils.findMethod(bean.getClass(), mockParam.getMethodName(),mockParam.getParamsType());

            if("bpmCenterServiceImpl".equals(mockParam.getBeanName()) &&
                    ("startProcess".equals(mockParam.getMethodName())
                            || "submitworklistitem".equals(mockParam.getMethodName())
                            || "rollBackAction".equals(mockParam.getMethodName())
                    )){
                List params = mockParam.getParams();
                Map map = (Map) params.get(0);
                Map win = (Map) map.get("win");
                String s = JacksonUtil.writeValueAsString(win);
                JSONObject jsonObject = JSONObject.parseObject(s);
                map.put("win",jsonObject);

                List<String> keyList = Arrays.asList("next_deal_name","copygive");
                for(String key : keyList){
                    if(map.get(key) == null || map.get(key) instanceof String) {
                        continue;
                    }
                    List next_deal_name = (List) map.get(key);
                    String next_deal_name_json = JacksonUtil.writeValueAsString(next_deal_name);
                    JSONArray jsonObject1 = JSONArray.parseArray(next_deal_name_json);
                    map.put(key,jsonObject1);
                }
            }

            //保存草稿
            if("bpmCenterServiceImpl".equals(mockParam.getBeanName()) && ("addDraft".equals(mockParam.getMethodName()))){
                List params = mockParam.getParams();
                Map map = (Map) params.get(0);
                List next_deal_name = (List) map.get("next_deal_name");
                String next_deal_name_json = JacksonUtil.writeValueAsString(next_deal_name);
                JSONArray jsonObject1 = JSONArray.parseArray(next_deal_name_json);
                map.put("next_deal_name",jsonObject1);
            }

            LOGGER.info("method:{}",method);
            int parameterCount = method.getParameterCount();
            if(parameterCount>0) {
                if(mockParam.getParams() == null) {
                    rs = ReflectionUtils.invokeMethod(method, bean, request);
                }else{
                    Object[] objects = mockParam.getParams().toArray();
                    rs = ReflectionUtils.invokeMethod(method, bean, objects);
                }

            }else{
                rs = ReflectionUtils.invokeMethod(method, bean);
            }


        }catch (Exception e){
            LOGGER.error("outer error : {}",e.getMessage(),e);
            String err = null;
            if(e.getMessage() == null && e instanceof java.lang.reflect.UndeclaredThrowableException) {
                err = ((java.lang.reflect.UndeclaredThrowableException)e).getUndeclaredThrowable().getMessage();
            }else{
                err = e.getMessage();
            }
            LOGGER.error("outer error : {}",err,e);
            return ApiResult.failMessage(err);
        }
        return rs;

    }

}
